import os

def getDependencies():
  deps = {}
  file = open('js/dependencies.txt', 'r')
  for line in file:
    name,files = getDependencyFromLine(line)
    if name:
      deps[name] = files
  file.close()
  return deps

def getDependencyFromLine(line):
  files = line.split()
  if len(files) > 0:
    name = files.pop(0)
    return name,files
  return None,None

def getFileListFromDependencies(deps):
  fileList = []
  fileSet = set()
  for name,files in deps.iteritems():
    addFileToList(fileList, fileSet, deps, name, files)
  return fileList

def addFileToList(fileList, fileSet, deps, name, files):
  for file in files:
    addFileToList(fileList, fileSet, deps, file, deps[file])

  if name not in fileSet:
    fileList.append(name)
    fileSet.add(name)

def makeJsFile(fileList):
  outFile = open('all.js', 'w')
  for file in fileList:
    inFile = open('js/' + file, 'r')
    outFile.write(inFile.read())
    inFile.close()
  outFile.close()

def makeJsDebugFile(fileList):
  outFile = open('all-debug.js', 'w')
  outFile.write('var head = document.getElementsByTagName(\'head\')[0];\n')
  outFile.write('function writeFile(file) {\n')
  outFile.write('  var script = document.createElement(\'script\');\n')
  outFile.write('  script.type = \'text/javascript\';\n')
  outFile.write('  script.src = file;\n')
  outFile.write('  head.appendChild(script);\n')
  outFile.write('}\n')
  for file in fileList:
    outFile.write('writeFile(\'lib/js/' + file + '\');\n')
  outFile.close()

os.chdir('../lib')
deps = getDependencies()
fileList = getFileListFromDependencies(deps)
makeJsFile(fileList)
os.system('python ../py/jsmin.py <all.js >all-min.js')
makeJsDebugFile(fileList)
os.chdir('../py')
